#pragma once
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
#include <string.h>
#include "nocopy.hpp"
#include <functional>

using func_t = std::function<std::string(std::string)>;

static const uint16_t defaultport = 8888;
static const int defaultsockfd = -1;
class UdpServer : public nocopy
{
public:
    // UdpServer(uint16_t port = defaultport, func_t func) //缺省参数只能放在后面
    UdpServer(func_t func, uint16_t port = defaultport)
    :_port(port), _sockfd(defaultsockfd), _HandleMessage(func)
    {}
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); //#include <sys/socket.h>
        if(_sockfd < 0)
        {
            exit(1);
        }
        struct sockaddr_in local; //#include <netinet/in.h>
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);

        int n = bind(_sockfd, (sockaddr*)&local, sizeof local);
        if(n < 0)
        {
            exit(2);
        }
    }
    void Start()
    {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer; // 让recvfrom知道大小
            memset(&peer, 0, sizeof(peer));
            int n = recvfrom(_sockfd, buffer, sizeof buffer - 1, 0, (sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                InetAddr addr(&peer);
                std::string result = _HandleMessage(buffer);
                std::cout << result << std::endl;
                sendto(_sockfd, result.c_str(), result.size(), 0, (sockaddr*)&peer, len);

                std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
            }
        }
    }
private:
    uint16_t _port;
    int _sockfd;
    func_t _HandleMessage;
};